var express = require('express');
var router = express.Router();
var db = require('../../data');
var multiparty = require('multiparty');
var fs = require('fs');
var util = require('util');
var config = require('config');
/* GET home page. */

var index = function(req, res, next){
  var session = req.session;
  var data = db.model;

  if(!session.suser || !session.suser.login){
    res.redirect('/uadmin/login');
  }else{

    data.basicFacts.findOne(function(err, data_){
      var returnData = {
        path: 'index',
        basicFacts : data_,
        user : session.suser
      };

      data.uad.find({}, function(err, data){
        if(err)
          returnData.table = [];
        else
          returnData.table = data;


        res.render('uadmin/index', returnData);
      });

    });

  };
};

var GET = {
  add: function(req, res, next){
    if(req.session.suser && req.session.suser.auid === -1)
      res.render('uadmin/add', {status: "1", msg: "1"});
    else
      next();
  }
};


var POST = {
  add: function(req, res, next){
    var arr = [req.body.a,req.body.b,req.body.c,req.body.d,req.body.e,req.body.f,req.body.g,req.body.h,req.body.r];
    var data = db.model;
    var uad = new data.uad({arr: arr});
    uad.save(function(err){
      if(err){
        res.render('uadmin/add', {status: false, msg: err});
        return false;
      };

      res.render('uadmin/add', {status: true, msg: 0});

    });
  }
};

var nodeExcel = require('excel-export');

var user_export = function(req, res, next){

  var conf ={};
  // uncomment it for style example
  // conf.stylesXmlFile = "styles.xml";
  conf.cols = [{
    caption:'手机号',
    type:'string',
    width: 200
  },{
    caption:'注册时间',
    type:'string',
    width: 200
  }];
  conf.rows = [];

  var data = db.model;
  //console.log();
  data.user.find({}, function(err, doc){
    for(var i in doc){
      var arr = [doc[i].phone];
      var time = new Date(doc[i].date);
      arr.push(time.getFullYear()+'/'+(time.getMonth()+1)+'/'+time.getDate()+' '+(time.getHours() < 10 ? '0'+time.getHours(): time.getHours())+':'+(time.getMinutes() < 10 ? '0'+time.getMinutes():time.getMinutes())+':'+(time.getSeconds() < 10 ? '0'+time.getSeconds(): time.getSeconds()));
      conf.rows.push(arr);
    }
    var result = nodeExcel.execute(conf);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
    res.end(result, 'binary');
  });



};

router.get('/', index);
router.get('/index', index);
router.get('/add', GET.add);
router.get('/index/add', GET.add);
router.get('/user_export', user_export);

router.post('/index/add', POST.add);

module.exports = router;
